package com.xinchao.ck_mips.filedownload;

import android.util.Log;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloadQueueSet;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.xinchao.ck_mips.model.IDownCallbackListener;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wq on 2019/4/29.
 * 节目下载类
 */
public class SingleDownload {
    private static SingleDownload mInstance = null;
    private FileDownloadListener mDownloadListener;

    private SingleDownload() {
    }

    public static SingleDownload getInstance() {
        if (null == mInstance) {
            synchronized (SingleDownload.class) {
                if (null == mInstance) {
                    mInstance = new SingleDownload();
                }
            }
        }

        return mInstance;
    }

    /**
     * 初始化下载对象
     * 单文件下载
     *
     * @param url      下载文件连接
     * @param filePath 本地保存文件路径
     * @return
     */
    public void downSingleFile(String url, String filePath, IDownCallbackListener mListener) {
        try {
            String host = url.substring(0, url.lastIndexOf("/") + 1);
            String name = url.substring(url.lastIndexOf("/") + 1);
            //对中文编码
            String downurl = host + URLEncoder.encode(name, "utf-8");
            BaseDownloadTask task = FileDownloader.getImpl().create(downurl)
                    .setPath(filePath).setCallbackProgressTimes(300)
                    .setMinIntervalUpdateSpeed(400)
                    .setAutoRetryTimes(3)
                    .setListener(createListener(mListener));
            task.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 多文件下载
     *
     * @param urls
     * @param filepaths
     * @return
     */
    public List<BaseDownloadTask> getMutiDownLoader(String[] urls, String[] filepaths) {
        List<BaseDownloadTask> list = new ArrayList<>();
        for (int i = 0; i < urls.length; i++) {
            list.add(FileDownloader.getImpl().create(urls[i]).setPath(filepaths[i]).setCallbackProgressTimes(0));
        }

        return list;
    }

    public FileDownloadListener createListener(IDownCallbackListener mListener) {
        return new FileDownloadSampleListener() {
            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                super.pending(task, soFarBytes, totalBytes);
                mListener.pending();
            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                super.progress(task, soFarBytes, totalBytes);
                Log.v("down", "下载中:" + soFarBytes + ";" + totalBytes);
                mListener.progressed();
            }

            @Override
            protected void blockComplete(BaseDownloadTask task) {
                super.blockComplete(task);
            }

            @Override
            protected void completed(BaseDownloadTask task) {
                super.completed(task);
                Log.v("down", "下载completed" + task.getUrl());
                mListener.completed(task.getUrl());
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                super.paused(task, soFarBytes, totalBytes);
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                super.error(task, e);
                mListener.error(task.getUrl(), e);
            }

            @Override
            protected void warn(BaseDownloadTask task) {
                super.warn(task);
            }
        };
    }

    public void getDownList(String[] urls, String[] filePaths, IDownCallbackListener mListener) {
        FileDownloadQueueSet queueSet = new FileDownloadQueueSet(createListener(mListener));
        FileDownloader.enableAvoidDropFrame();
        queueSet.setAutoRetryTimes(3);//失败，重试次数
        //串行下载
        queueSet.disableCallbackProgressTimes();
        queueSet.downloadSequentially(getMutiDownLoader(urls, filePaths));
        queueSet.setCallbackProgressMinInterval(300);
        queueSet.start();
    }

    public void stop() {
        FileDownloader.getImpl().pause(mDownloadListener);
    }

}
